package com.goods.business.service.imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.goods.business.mapper.*;
import com.goods.business.service.OutStockService;
import com.goods.common.error.BusinessCodeEnum;
import com.goods.common.error.BusinessException;
import com.goods.common.model.business.*;
import com.goods.common.utils.JWTUtils;
import com.goods.common.vo.business.ConsumerVO;
import com.goods.common.vo.business.OutStockDetailVO;
import com.goods.common.vo.business.OutStockItemVO;
import com.goods.common.vo.business.OutStockVO;
import com.goods.common.vo.system.PageVO;
import com.google.gson.JsonObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: Mr.Cao
 * @DateTime: 2021/11/9 17:20
 * BMW F750GS
 **/
@Service
public class OutStockServiceImpl implements OutStockService {

    @Autowired
    private OutStockMapper outStockMapper;
    @Autowired
    private ConsumerMapper consumerMapper;
    @Autowired
    private OutStockInfoMapper outStockInfoMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductStockMapper productStockMapper;

    /**
     * 分页 查询发放记录
     */
    @Override
    public PageVO findOutStockList(Map queryMap) {
        String pageNum = (String) queryMap.get("pageNum");
        String pageSize = (String) queryMap.get("pageSize");
        //分页查询
        Page<Object> page = PageHelper.startPage(Integer.valueOf(pageNum), Integer.valueOf(pageSize));

        //条件查询
        Example o = new Example(OutStock.class);
        Example.Criteria criteria = o.createCriteria();
        //发放状态: 0:已发放 1:回收站 2 待审核
        String status = (String) queryMap.get("status");
        if (status.equals("1") || status.equals("2") || status.equals("0")) {
            criteria.andEqualTo("status", status);
        }
        //发放类型
        String type = (String) queryMap.get("type");
        if (!StringUtils.isEmpty(type)) {
            criteria.andEqualTo("type", type);
        }
        //发放单号
        String outNum = (String) queryMap.get("outNum");
        if (!StringUtils.isEmpty(outNum)) {
            criteria.andLike("outNum", "%" + outNum + "%");
        }
        List<OutStock> outStocks = outStockMapper.selectByExample(o);
        //转换Vo
        List<OutStockVO> outStockVOS = new ArrayList<>();
        for (OutStock outStock : outStocks) {
            OutStockVO outStockVO = new OutStockVO();
            BeanUtils.copyProperties(outStock, outStockVO);
            //获取发放的地点
            Consumer consumer = consumerMapper.selectByPrimaryKey(outStock.getConsumerId());
            outStockVO.setName(consumer.getName());
            //联系方式
            outStockVO.setPhone(consumer.getPhone());

            outStockVOS.add(outStockVO);
        }
        return new PageVO(page.getTotal(), outStockVOS);
    }

    /**
     * 查询发放明细
     */
    @Override
    public OutStockDetailVO detail(long id, Integer pageNum) {
        OutStockDetailVO result = new OutStockDetailVO();
        //查询 发放主表
        OutStock outStock = outStockMapper.selectByPrimaryKey(id);
        //转Vo
        BeanUtils.copyProperties(outStock, result);

        //查新发放明细表 根据outNum outStockInfo表
        Example outStockInfoExample = new Example(OutStockInfo.class);
        outStockInfoExample.createCriteria().andEqualTo("outNum", outStock.getOutNum());
        List<OutStockInfo> outStockInfoList = outStockInfoMapper.selectByExample(outStockInfoExample);
        for (OutStockInfo outStockInfo : outStockInfoList) {
            //查询每项商品详情
            //分页
            Page<Object> page = PageHelper.startPage(pageNum, 5);

            Example productExample = new Example(Product.class);
            productExample.createCriteria().andEqualTo("pNum", outStockInfo.getPNum());
            Product product = productMapper.selectOneByExample(productExample);
            //转换Vo
            OutStockItemVO outStockItemVO = new OutStockItemVO();
            BeanUtils.copyProperties(product, outStockItemVO);
            outStockItemVO.setCount(outStockInfo.getProductNumber());
            result.setTotal(page.getTotal());
            result.getItemVOS().add(outStockItemVO);
        }
        //查询消费记录信息
        Consumer consumer = consumerMapper.selectByPrimaryKey(outStock.getConsumerId());
        //转Vo
        ConsumerVO consumerVO = new ConsumerVO();
        BeanUtils.copyProperties(consumer, consumerVO);
        result.setConsumerVO(consumerVO);
        return result;
    }

    /**
     * 新增发放记录
     */
    @Transactional
    @Override
    public void addOutStock(OutStockVO outStockVO, HttpServletRequest request) {
        //保存主表 使用
        OutStock outStock = new OutStock();

        BeanUtils.copyProperties(outStockVO, outStock);

        //如果是未知物资来源,保存物资来源
        if (outStockVO.getConsumerId() == null || outStockVO.getConsumerId() == 0) {
            //位置物去向,保存物资去向
            Consumer consumer = new Consumer();
            consumer.setName(outStockVO.getName());
            consumer.setAddress(outStockVO.getAddress());
            consumer.setCreateTime(new Date());
            consumer.setModifiedTime(new Date());
            consumer.setPhone(outStockVO.getPhone());
            consumer.setSort(outStockVO.getSort());
            consumer.setContact(outStockVO.getContact());
            consumerMapper.insert(consumer);//主键回填
            //消费去向Id
            outStock.setConsumerId(consumer.getId());
        }

        //随机生成出库单号
        String outNum = UUID.randomUUID().toString().replace("-", "");
        //商品总数量
        int productTotal = 0;
        //保存领取的物资表 outStockInfo表
        List<Map> products = outStockVO.getProducts();
        for (Map product : products) {
            Integer productId = (Integer) product.get("productId");
            Integer productNumber = (Integer) product.get("productNumber");
            Product productById = productMapper.selectByPrimaryKey(productId);
            OutStockInfo outStockInfo = new OutStockInfo();
            //出库编号
            outStockInfo.setOutNum(outNum);
            //商品编号
            outStockInfo.setPNum(productById.getPNum());
            //商品数量
            outStockInfo.setProductNumber(productNumber);
            //创建和修改日期
            outStockInfo.setCreateTime(new Date());
            outStockInfo.setModifiedTime(new Date());
            outStockInfoMapper.insert(outStockInfo);//主键回填
            productTotal += productNumber;
        }

        //保存出库表 主表outStock表
        //出库单号
        outStock.setOutNum(outNum);
        //获取操作员名称
        String authorization = request.getHeader("Authorization");
        String username = JWTUtils.getUsername(authorization);
        outStock.setOperator(username);
        //新建时间
        outStock.setCreateTime(new Date());
        //商品总数量
        outStock.setProductNumber(productTotal);
        //设置状态为 待审核
        outStock.setStatus(2);
        outStockMapper.insert(outStock);
    }

    /**
     * 审核通过
     */
    @Transactional
    @Override
    public void publish(long id) throws BusinessException {
        OutStock outStock = outStockMapper.selectByPrimaryKey(id);
        if (outStock != null) {
            outStock.setStatus(0);//设置状态为 正常
            outStockMapper.updateByPrimaryKey(outStock);
            //查询商品集合 根据inNum
            Example exampleOutStockInfo = new Example(OutStock.class);
            exampleOutStockInfo.createCriteria().andEqualTo("outNum", outStock.getOutNum());
            List<OutStockInfo> outStockInfoList = outStockInfoMapper.selectByExample(exampleOutStockInfo);
            for (OutStockInfo outStockInfo : outStockInfoList) {
                //更新商品库存
                //先查询商品库存,根据Pnum
                Example exampleProductStock = new Example(ProductStock.class);
                exampleProductStock.createCriteria().andEqualTo("pNum", outStockInfo.getPNum());
                ProductStock productStock = productStockMapper.selectOneByExample(exampleProductStock);
                if (productStock != null) {//有库存记录
                   //判断库存记录是否足够本次消费
                    Long productStockStock = productStock.getStock();//当前库存
                    Integer productNumber = outStockInfo.getProductNumber();//本次消费数量
                    if (productStockStock>=productNumber){
                        //更新库存
                        productStock.setStock(productStockStock - productNumber);
                        productStockMapper.updateByPrimaryKey(productStock);
                    }else {
                        //库存不够时,不允许消费, 抛出异常
                        throw new BusinessException(BusinessCodeEnum.PRODUCT_STOCK_ERROR);
                    }

                }
            }
        }
    }

    /**
     * 审核不通过, 删除
     */
    @Override
    public void delete(long id) {
        OutStock outStock = outStockMapper.selectByPrimaryKey(id);
        if (outStock != null && outStock.getStatus().equals(1)) {
            outStockMapper.deleteByPrimaryKey(id);
        }
    }

    /**
     * 移除进入回收站
     */
    @Override
    public void remove(long id) {
        OutStock inStock = outStockMapper.selectByPrimaryKey(id);
        if (inStock != null) {
            inStock.setStatus(1);//设置状态为 回收站
            outStockMapper.updateByPrimaryKey(inStock);
        }
    }

    /**
     * 还原: 恢复到正常
     */
    @Override
    public void back(long id) {
        OutStock outStock = outStockMapper.selectByPrimaryKey(id);
        if (outStock != null && outStock.getStatus().equals(1)) {
            outStock.setStatus(0);//设置状态为 回收站
            outStockMapper.updateByPrimaryKey(outStock);
        }
    }
}
